package com.aop.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * @author xinwang
 * @date 2020/2/23 14:55
 **/
//手动获取事务
@Component
@Scope(value = "prototype") //每个事务都是新的实例 目的解决线程安全问题
public class TransactionUtils {

    @Autowired
    private DataSourceTransactionManager transactionManager;
    //全局事务状态
    private TransactionStatus transaction;
    //开启事务
    public TransactionStatus begin() {
        System.out.println("开启事务");
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());
        return transaction;
    }

    //提交事务
    public void commit(TransactionStatus transaction) {
        System.out.println("提交事务");
        transactionManager.commit(transaction);
    }

    //回滚事务
    public void rollback() {
        System.out.println("回滚事务");
        transactionManager.rollback(transaction);
    }


}
